package app.auto.runner.base.widget;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;

import com.aliang.auto.R;

import app.auto.runner.base.DipUtil;
import app.auto.runner.base.intf.FunCallback;

/**
 * @Title 流式布局
 * @Authour zhoujp
 * @Time 2016年8月3日 上午9:40:48
 */
public class FloatLayout extends ViewGroup {
    public Map<Integer, String> txt_type = new TreeMap<Integer, String>();
    private static final int TXT_TYPE = R.id.TXT_TYPE;
    // 存放所有子View
    private List<List<View>> mAllChildViews = new ArrayList<>();
    // 每一行的高度
    private List<Integer> mLineHeight = new ArrayList<>();
    private List mNames = new ArrayList<>();
    private int topMargin;
    private int bottomMargin;


    Map<View, FunCallback> viewCallback = new TreeMap<>();
    private int selectedbgid;
    private int[] padding;
    private int text_item_black;

    public FloatLayout setSelectedbgid(int selectedbgid) {
        this.selectedbgid = selectedbgid;
        return this;
    }

    public List<String> getText() {
        return mNames;
    }

    public void addLast(String txt) {
        mNames.add(mNames.size() - 1, txt);
    }


    public List<String> returnvalue = new ArrayList<>();

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void addFirstNotified(String txt, String txt_type) {
        mNames.add(0, txt);
        returnvalue.add(0, txt);
        notifyChanged();
        getChildAt(0).setTag(TXT_TYPE, txt_type);

    }


    @RequiresApi(api = Build.VERSION_CODES.M)
    public void clearReturnValue() {
        mNames.removeAll(returnvalue);
        returnvalue.clear();
        notifyChanged();
    }

    public boolean hasReturnValue() {
        return !returnvalue.isEmpty();
    }

    public FloatLayout(Context context) {
        this(context, null);
    }

    public boolean single_mode = false;

    public FloatLayout setSingleMode(boolean single_mode) {
        this.single_mode = single_mode;
        return this;
    }

    public FloatLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public FloatLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    FunCallback funCallback;

    public FloatLayout setOnClickCallback(FunCallback funCallback) {
        this.funCallback = funCallback;
        return this;
    }

    public int unselectedbgid = -1;

    public FloatLayout setUnselectedbgid(int unselectedbgid) {
        this.unselectedbgid = unselectedbgid;
        return this;
    }

    Map view_idx = new HashMap();


    @RequiresApi(api = Build.VERSION_CODES.M)
    public void notifyChanged() {
        setText(mNames, new TreeMap<String, String>());

    }


    public static final String TYPE_VARTYPE = "TYPE_VARTYPE";
    public static final String TYPE_VARNAME = "TYPE_VARNAME";
    public static final String TYPE_OPTEQUAL = "TYPE_OPTEQUAL";

    @RequiresApi(api = Build.VERSION_CODES.M)
    public FloatLayout setText(List mName) {
        return setText(mName, null);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public FloatLayout setText(List mName, Map type) {
        this.mNames = mName;
        removeAllViews();
        view_idx.clear();
        MarginLayoutParams lp = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        DipUtil.initCtx(getContext());

//        lp.leftMargin = 1;
//        lp.rightMargin = 1;
        lp.topMargin = 5;
        lp.bottomMargin = 5;
        for (int i = 0; i < mNames.size(); i++) {
            if (mNames.get(i) instanceof String) {

                TextView view = (TextView) LayoutInflater.from(getContext()).inflate(text_item_black != 0 ? text_item_black : R.layout.text_item, null);
                if (unselectedbgid != -1) {
                    view.setBackgroundResource(unselectedbgid);
                }
                view_idx.put(view, i);

                view.setText(mNames.get(i).toString());
                if (type != null) {

                    String t = (String) type.get(mNames.get(i));
                    if (t != null) {
                        view.setTag(TXT_TYPE, t);
                    }
                }
                if (view.getText().toString().trim().equals(";")
                ) {

                } else if (view.getText().toString().trim().equals("添加语句")
                ) {
                    view.setBackgroundResource(R.drawable.auto_background_rect_green);
                    view.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (funCallback != null) {
                                funCallback.onCallback(v, view_idx.get(v));
                            }
                        }
                    });
                } else {
                    view.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!single_mode) {

                                if (v.getTag() == null) {
                                    v.setBackgroundResource(selectedbgid);
                                    ((TextView) v).setTextColor(Color.WHITE);
                                    v.setTag(true);

                                } else {
                                    if ((boolean) v.getTag()) {
                                        v.setBackgroundResource(unselectedbgid);
                                        ((TextView) v).setTextColor(Color.BLACK);
                                        v.setTag(false);

                                    } else {
                                        v.setBackgroundResource(selectedbgid);
                                        ((TextView) v).setTextColor(Color.WHITE);
                                        v.setTag(true);

                                    }
                                }
                            } else {
                                disablebakgrounds();
                                v.setBackgroundResource(selectedbgid);
                                ((TextView) v).setTextColor(Color.WHITE);
                                v.setTag(true);
                            }
                            if (funCallback != null) {
                                funCallback.onCallback(((TextView) v).getText().toString(), v.getTag());
                            }
                        }
                    });

                }
//            view.setBackgroundDrawable(getResources().getDrawable(R.drawable.textshap));
                if (view.getText().toString().trim().equals("添加语句")) {
                    lp.leftMargin = 5;
                } else {
                    lp.leftMargin = 0;

                }
                if (leftMargin != 0) {
                    lp.leftMargin = leftMargin;
                }
                if (bottomMargin != 0) {
                    lp.bottomMargin = bottomMargin;
                }
                if (rightMargin != 0) {
                    lp.rightMargin = rightMargin;
                }
                if (topMargin != 0) {
                    lp.topMargin = topMargin;
                }
                if (padding != null) {
                    view.setPadding(padding[0], padding[1], padding[2], padding[3]);
                }
                addView(view, lp);
            } else if (mNames.get(i) instanceof List) {

            }

        }

        return this;
    }

    private void disablebakground(View view) {
        view.setTag(false);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public FloatLayout setText(Map type) {
        this.mNames = new ArrayList(type.keySet());
        removeAllViews();
        view_idx.clear();
        MarginLayoutParams lp = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        DipUtil.initCtx(getContext());

//        lp.leftMargin = 1;
//        lp.rightMargin = 1;
        lp.topMargin = 5;
        lp.bottomMargin = 5;
        for (int i = 0; i < mNames.size(); i++) {
            if (mNames.get(i) instanceof String) {

                TextView view = (TextView) LayoutInflater.from(getContext()).inflate(R.layout.text_item, null);
                if (unselectedbgid != -1) {
                }
                view_idx.put(view, i);

                view.setText(mNames.get(i).toString());
                if (type != null) {

                    String t = (String) type.get(mNames.get(i));
                    if (t != null) {
                        view.setTag(TXT_TYPE, t);
                        if (t.equals("selected")) {
                            view.setBackgroundResource(selectedbgid);

                        } else if (t.equals("unselected")) {
                            view.setBackgroundResource(unselectedbgid);

                        }
                    }
                }
                if (view.getText().toString().trim().equals(";")
                ) {

                } else if (view.getText().toString().trim().equals("添加语句")
                ) {
                    view.setBackgroundResource(R.drawable.auto_background_rect_green);
                    view.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (funCallback != null) {
                                funCallback.onCallback(v, view_idx.get(v));
                            }
                        }
                    });
                } else {
                    view.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (v.getTag() == null) {
                                v.setBackgroundResource(unselectedbgid);
                                ((TextView) v).setTextColor(Color.BLACK);

                            } else {
                                if ((boolean) v.getTag()) {
                                    v.setBackgroundResource(selectedbgid);
                                    ((TextView) v).setTextColor(Color.WHITE);

                                } else {
                                    v.setBackgroundResource(unselectedbgid);
                                    ((TextView) v).setTextColor(Color.BLACK);

                                }
                            }
                            if (funCallback != null) {
                                funCallback.onCallback(v, view_idx.get(v));
                            }
                        }
                    });

                }
//            view.setBackgroundDrawable(getResources().getDrawable(R.drawable.textshap));
                if (view.getText().toString().trim().equals("添加语句")) {
                    lp.leftMargin = 5;
                } else {
                    lp.leftMargin = 0;

                }
                addView(view, lp);
            } else if (mNames.get(i) instanceof List) {

            }

        }

        return this;
    }

    @Override
    public String toString() {

        String line = "";
        for (int i = 0; i < mAllChildViews.size(); i++) {
            List<View> list = mAllChildViews.get(i);
            for (int j = 0; j < list.size(); j++) {
                line += ((TextView) list.get(j)).getText().toString() + " ";
            }
            line += "\n";
        }
        return line;
    }

    public void disablebakgrounds() {
        for (Object v : view_idx.keySet()) {
            if (((TextView) v).getText().toString().trim().equals("+")) {

            } else {
                ((View) v).setBackgroundResource(unselectedbgid);
                ((View) v).setTag(false);
                ((TextView) v).setTextColor(Color.BLACK);

            }
        }
    }

    public void addText(String text) {

    }

    public void addText(int index, String text) {

    }


    public void delAt(int index) {

    }

    public void set(int index, String text) {

    }

    public int indexOf(String text) {
        return -1;
    }

    public String get(int index) {
        return "";
    }

    int leftMargin;
    int rightMargin;

    public FloatLayout setLeftMargin(int leftMargin) {
        this.leftMargin = leftMargin;
        return this;
    }

    public FloatLayout setRightMargin(int rightMargin) {
        this.rightMargin = rightMargin;
        return this;
    }

    public FloatLayout setTopMargin(int topMargin) {
        this.topMargin = topMargin;
        return this;
    }

    public FloatLayout setBottomMargin(int bottomMargin) {
        this.bottomMargin = bottomMargin;
        return this;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 父控件传进来的宽度和高度以及对应的测量模式
        int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
        int modeWidth = MeasureSpec.getMode(widthMeasureSpec);
        int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);
        int modeHeight = MeasureSpec.getMode(heightMeasureSpec);
// 如果当前ViewGroup的宽高为wrap_content的情况
        int width = 0;// 自己测量的 宽度
        int height = 0;// 自己测量的高度
// 记录每一行的宽度和高度
        int lineWidth = 0;
        int lineHeight = 0;
// 获取子view的个数
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
// 测量子View的宽和高
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
// 得到LayoutParams
            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(-1, -2);
// 子View占据的宽度
            int childWidth = child.getMeasuredWidth() + leftMargin + rightMargin;
// 子View占据的高度
            int childHeight = child.getMeasuredHeight() + topMargin + bottomMargin;
// 换行时候
            if (lineWidth + childWidth > sizeWidth) {
// 对比得到最大的宽度
                width = Math.max(width, lineWidth);
// 重置lineWidth
                lineWidth = childWidth;
// 记录行高
                height += lineHeight;
                lineHeight = childHeight + topMargin + bottomMargin;
            } else {// 不换行情况
// 叠加行宽
                lineWidth += childWidth;
// 得到最大行高
                lineHeight = Math.max(lineHeight, childHeight);
            }
// 处理最后一个子View的情况
            if (i == childCount - 1) {
                width = Math.max(width, lineWidth);
                height += lineHeight;
            }
        }
// wrap_content
        setMeasuredDimension(modeWidth == MeasureSpec.AT_MOST ? sizeWidth : width, height);
//        setMeasuredDimension(modeWidth == MeasureSpec.UNSPECIFIED ? sizeWidth : width,
//                modeHeight == MeasureSpec.UNSPECIFIED ? sizeHeight : height);
//        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
//        getLayoutParams().height = modeHeight;
//        invalidate();
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mAllChildViews.clear();
        mLineHeight.clear();
// 获取当前ViewGroup的宽度
        int width = getWidth();
        int lineWidth = 0;
        int lineHeight = 0;
// 记录当前行的view
        List<View> lineViews = new ArrayList<View>();
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
            int childWidth = child.getMeasuredWidth();
            int childHeight = child.getMeasuredHeight();
// 如果需要换行
            if (childWidth + lineWidth + lp.leftMargin + lp.rightMargin > width) {
// 记录LineHeight
                mLineHeight.add(lineHeight);
// 记录当前行的Views
                mAllChildViews.add(lineViews);
// 重置行的宽高
                lineWidth = 0;
                lineHeight = childHeight + lp.topMargin + lp.bottomMargin;
// 重置view的集合
                lineViews = new ArrayList();
            }
            lineWidth += childWidth + lp.leftMargin + lp.rightMargin;
            lineHeight = Math.max(lineHeight, childHeight + lp.topMargin + lp.bottomMargin);
            lineViews.add(child);
        }
// 处理最后一行
        mLineHeight.add(lineHeight);
        mAllChildViews.add(lineViews);
// 设置子View的位置
        int left = 0;
        int top = 0;
// 获取行数
        int lineCount = mAllChildViews.size();
        for (int i = 0; i < lineCount; i++) {
// 当前行的views和高度
            lineViews = mAllChildViews.get(i);
            lineHeight = mLineHeight.get(i);
            for (int j = 0; j < lineViews.size(); j++) {
                View child = lineViews.get(j);
// 判断是否显示
                if (child.getVisibility() == View.GONE) {
                    continue;
                }
                MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
                int cLeft = left + lp.leftMargin;
                int cTop = top + lp.topMargin;
                int cRight = cLeft + child.getMeasuredWidth();
                int cBottom = cTop + child.getMeasuredHeight();
// 进行子View进行布局
                child.layout(cLeft, cTop, cRight, cBottom);
                left += child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin;
            }
            left = 0;
            top += lineHeight;
        }
    }

    /**
     * 与当前ViewGroup对应的LayoutParams
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    public FloatLayout setpadding(int... fromDip) {
        this.padding = fromDip;

        return this;
    }

    public FloatLayout setItem(int text_item_black) {
        this.text_item_black = text_item_black;
        return this;

    }
}